package com.ynwt.service;

import com.github.sd4324530.fastweixin.api.CustomAPI;
import com.github.sd4324530.fastweixin.api.TemplateMsgAPI;
import com.github.sd4324530.fastweixin.api.entity.TemplateMsg;
import com.github.sd4324530.fastweixin.api.entity.TemplateParam;
import com.github.sd4324530.fastweixin.message.TextMsg;
import com.ynwt.domain.Event;
import com.ynwt.domain.UserEvent;
import com.ynwt.constant.CacheConst;
import com.ynwt.constant.EventType;
import com.ynwt.constant.RedisKey;
import com.ynwt.repository.EventDao;
import com.ynwt.repository.UserEventDao;
import com.ynwt.util.TimeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.redis.core.BoundZSetOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by huangying on 2017/6/1.
 */
@Service
public class JobServiceImpl implements JobService {

    @Override
    public void sendSignTemplateMsg() {

        int count = 0;//用来测试发了多少条模版消息

        long start = TimeUtil.startOfDateBaseNow(7).getTime();
        long now = new Date().getTime();

        //获取7天内的有过签到操作的用户
        BoundZSetOperations ops = redisTemplate.boundZSetOps(RedisKey.SIGN_OPERATION_RECORD);
        Set<String> set = ops.rangeByScore(start, now);

        //如果今天没有签到，则发送签到记录
        for (String openid : set) {
            if (!eventService.hasSignedToday(openid)) {
                count++;
                sendSignTemplateMsgToOne(openid);
            }
        }
        //发给黄蓥
        customAPI.sendCustomMessage("oYIcvxJkVReWsrJj24_z4ylGU5-o", new TextMsg("今天一共发了" + count + "条签到提醒模版消息"));
    }

    /**
     * 发送签到提醒给某个用户
     * @param openid
     */
    public void sendSignTemplateMsgToOne(String openid) {

        //获取连续签到的次数
        int successionSignTimes;
        List<UserEvent> userEvents = userEventDao.findByUserOpenidAndDateGreaterThanAndEventKeyStartingWith(openid, TimeUtil.startOfDateBaseNow(1), EventType.PREFIX_SIGN);
        if (userEvents.size() < 1) {
            successionSignTimes = 0;
        } else {
            successionSignTimes = Integer.parseInt(userEvents.get(0).getContent());
        }

        //设置发送的内容
        Map map = new HashMap();
        TemplateParam first = new TemplateParam();
        TemplateParam keyword1 = new TemplateParam();
        TemplateParam keyword2 = new TemplateParam();
        TemplateParam remark = new TemplateParam();
        first.setColor("#FFA500");
        keyword1.setColor("#FF7F00");
        keyword2.setColor("#FF7F00");
        remark.setColor("#FFA500");
        first.setValue("亲爱的环球小伙伴，学习贵在持之以恒，21天养成一个好习惯，环球数据与你同行，希望你能每天早起打卡学习！");
        keyword1.setValue(successionSignTimes + "天");
        keyword2.setValue(getEndTimeOfSign());
        remark.setValue("如学习、生活上有任何困难，可以加云逸未来志愿者001微信：yunyiweilai001,值班的志愿者将尽其所能的帮助您！");
        map.put("first", first);
        map.put("keyword1", keyword1);
        map.put("keyword2", keyword2);
        map.put("remark", remark);

        //设置模版消息参数
        TemplateMsg msg = new TemplateMsg();
        msg.setUrl("http://mp.weixin.qq.com/s/pRayNPk02h70DzyXC-ZkEQ");
        msg.setTouser(openid);
        msg.setTemplateId(signTemplateId);
        msg.setData(map);

        //发送模版消息
        templateMsgAPI.send(msg);
    }

    /**
     * 获取结束签到时间
     * @return
     */
    @Cacheable(value = "getEndTimeOfSign", keyGenerator = CacheConst.KEY_GENERATOR)
    public String getEndTimeOfSign() {
        Pageable pageable = new PageRequest(0, 1);
        Page<Event> page = eventDao.findByKeyStartingWithOrderByEndTimeDesc(EventType.PREFIX_SIGN, pageable);
        String signEndTimeStr = new SimpleDateFormat("HH:mm:ss").format(page.getContent().get(0).getEndTime());
        return signEndTimeStr;
    }




    @Autowired
    private UserEventDao userEventDao;

    @Autowired
    private EventDao eventDao;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private EventService eventService;

    @Autowired
    private CustomAPI customAPI;

    @Autowired
    private TemplateMsgAPI templateMsgAPI;

    @Value("${weixin.signTemplateId}")
    private String signTemplateId;

    @Value("${weixin.courseTemplateId}")
    private String courseTemplateId;
}
